package cn.liuxue.lifecircle.http;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.widget.TextView;

public class ClientService implements Runnable{
	
	private String SERVER_ADDRESS = "";
	private int SERVER_PORT = 9999;
	private Socket socket;
	private BufferedReader in = null;
	private PrintWriter out = null;
	
	private TextView tv = null;
	
	public ClientService() {
		try {
			socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			
			if (socket.isConnected()) {
				if (!socket.isOutputShutdown()) {
					out.println(tv.getText());
				}
			}
		
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread(this).start();
		
	}
	
	private void showMsg(String msg) {
		tv.setText(tv.getText() + msg);
	}

	@Override
	public void run() {
		String msg = null;
		while(true) {
			
			try {
				if (socket.isConnected()) {
					if (!socket.isInputShutdown()) {
						if ((msg = in.readLine()) != null) {
							msg += "/n";
							this.showMsg(msg);
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		
	}

}
